package sm.test;

import java.io.InputStream;
import java.sql.Blob;
import java.util.List;

import org.apache.mina.core.buffer.IoBuffer;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import sm.codec.DBDictCodec;
import sm.codec.api.Codec;
import sm.dbdict.def.DBDict;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class ShowDBDict2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		Codec codec = new DBDictCodec();
		SessionFactory sessionFactory = new Configuration().configure()
				.buildSessionFactory();
		Session session = sessionFactory.openSession();

		String sql = "select NAME, DESCRIPTORPRGN from DBDICTM1 where NAME = 'Object'";
		SQLQuery query = session.createSQLQuery(sql);
		List<Object> result = query.list();
		for (Object obj : result) {
			Object[] row = (Object[]) obj;
			System.out.println("name: " + row[0]);

			Blob blob = (Blob) row[1];
			int length = (int) blob.length();
			byte[] bytes = new byte[length];
			InputStream is = blob.getBinaryStream();
			is.read(bytes);
			is.close();

			IoBuffer buffer = IoBuffer.wrap(bytes);
			DBDict des = (DBDict) codec.decode(buffer);
			Gson gson = new GsonBuilder().setPrettyPrinting().create();
			System.out.println(gson.toJson(des));
		}

		session.close();
	}

}
